<!--
生产出库单明细页
-->
<template>
	<a-modal title="出库单详情" :width="1300" :visible="visible" :confirmLoading="confirmLoading" :footer="null"
		@ok="handleSubmit" @cancel="handleCancel">
		<a-card :bordered="false">
			<div class="table-page-search-wrapper">
				<a-form layout="inline">
					<a-row :gutter="48">

						<a-col :md="8" :sm="24" v-if="false">
							<a-form-item label="订单ID">
								<a-input v-model="queryParam.orderId" placeholder="请输入订单ID" />
							</a-form-item>
						</a-col>

					</a-row>
				</a-form>
			</div>

			<s-table ref="table" size="default" :columns="columns" :data="loadData" :alert="true" :showPagination="false">
				<template slot="materialModelNumber" slot-scope="text, record">
					{{ record.material ? record.material.materialModelNumber : '' }}
				</template>
				<!-- <span slot="image" slot-scope="text">
					<image-preview :images="text" />
				</span> -->
				<span slot="image" slot-scope="text,record">
					<image-preview1 :images="text" :imageUrl="record.material.imageUrl" />
				</span>
				<template slot="normalNumber" slot-scope="text, record">
					<a-input-number v-model:value="record.normalNumber" :step="1" :min="0" style="width: 67px;" />
				</template>
				<template slot="extraNumber" slot-scope="text, record">
					<a-input-number v-model:value="record.extraNumber" :step="1" :min="0" style="width: 67px;" />
				</template>
				<span slot="action" slot-scope="text, record">
					<a @click="$refs.outTimelineForm.show(record)">出库记录(包材未优化)</a>
				</span>
			</s-table>

			<add-form ref="addForm" @ok="handleOk" />
			<out-timeline-form ref="outTimelineForm" />
		</a-card>
	</a-modal>
</template>

<script>
import { STable } from '@/components'
import { page, del, add, listResult } from '@/api/modular/main/emsordermaterial/emsOrderMaterialManage'
import { addOutOrderForProductionOrder } from '@/api/modular/main/emsorder/emsOrderManage'
import addForm from '@/views/main/emsordermaterial/emsOrderMaterialAddFormOutOrder'
import editForm from '@/views/main/emsordermaterial/emsOrderMaterialEditForm'
import outTimelineForm from '@/views/main/emsordermaterial/emsOrderMaterialOutTimelineForm'
import materialForm from '@/views/main/emsmaterial/emsMaterialIndex'
import emsMaterialIndex1 from '@/views/main/emsmaterial/emsMaterialIndex1'
import productAddForm from '@/views/main/emsorder/emsOrderProductAddForm'
import productEditForm from '@/views/main/emsorder/emsOrderProductEditForm'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { MATERIAL_TYPE_ENUM, ORDER_TYPE_ENUM } from '@/utils/util'

export default {
	components: {
		STable,
		addForm,
		editForm,
		materialForm,
		emsMaterialIndex1,
		productAddForm,
		productEditForm,
		outTimelineForm,
	},
	props: {
		readonly: false,
	},
	data() {
		return {
			title: null,
			advanced: false, // 高级搜索 展开/关闭
			queryParam: {},  // 查询参数
			viewState: '',
			columns: [
				{
					title: '产品',
					dataIndex: 'productName',
				},
				{
					title: 'BOM',
					customRender: (text, record, index) => record.bomName || `/`
				},
				{
					title: '物料',
					dataIndex: 'materialName'
				},
				{
					title: '规格',
					dataIndex: 'materialModelNumber',
					scopedSlots: { customRender: 'materialModelNumber' }
				},
				{
					title: '图片',
					dataIndex: 'image',
					scopedSlots: { customRender: 'image' }
				},
				{
					title: '物号',
					dataIndex: 'materialCode'
				},
				{
					title: '领用方',
					dataIndex: 'classGroupName'
				},
				{
					title: '正常出库数量',
					dataIndex: 'number'
				},
				{
					title: '额外出库数量',
					dataIndex: 'extraNumber'
				},
			],
			// 加载数据方法 必须为 Promise 对象
			loadData: parameter => {
				return page(Object.assign(parameter, this.queryParam)).then((res) => {
					res.data.rows.forEach(value => {
						value.normalNumber = 0
					})
					return res.data
				})
			},
			selectedRowKeys: [],
			selectedRows: [],
			defaultExpandedKeys: [],
			replaceFields: {
				key: 'id',
			},
			visible: false,
			confirmLoading: false,
			emsOrder: null,
			extra: null,
		}
	},
	watch: {
		emsOrder() {
			let _this = this
			setTimeout(function () {
				_this.$refs.table.refresh()
			}, 100)
		}
	},
	computed: {
		token() {
			return Vue.ls.get(ACCESS_TOKEN)
		},
		MATERIAL_TYPE_ENUM() {
			return MATERIAL_TYPE_ENUM
		}
	},
	methods: {
		show(record, title, viewState, extra) {
			this.visible = true
			this.emsOrder = record
			this.title = title
			this.viewState = viewState
			this.extra = extra
			this.queryParam = Object.assign(this.queryParam, extra)

			this.queryParam.orderId = record.orderId
			this.queryParam.pageSize = -1

			setTimeout(() => {
				this.handleOk()
			}, 100)
		},
		del(record) {
			del(record).then((res) => {
				if (res.success) {
					this.$message.success('删除成功')
					this.$refs.table.refresh()
				} else {
					this.$message.error('删除失败：' + res.message)
				}
			}).catch((err) => {
				this.$message.error('删除错误：' + err.message)
			})
		},
		toggleAdvanced() {
			this.advanced = !this.advanced
		},
		handleOk() {
			this.$refs.table.refresh()
		},
		onSelectChange(selectedRowKeys, selectedRows) {
			this.selectedRowKeys = selectedRowKeys
			this.selectedRows = selectedRows
		},
		handleSubmit() {
			let emsOrder = this.emsOrder
			let $data = this.$refs.table.$data
			$data = $data.localDataSource

			let orderMaterials = $data.map(value => {
				return Object.assign({}, value, {
					sourceOrderId: emsOrder.orderId,
					sourceOrderMaterialId: value.orderMaterialId,
					number: value.normalNumber,
					extraNumber: value.extraNumber,
				})
			})

			let orderBean = {
				orderId: '',
				sourceOrderId: emsOrder.orderId,
				orderParentId: '',
				orderPids: '',
				orderNumber: '',
				orderType: ORDER_TYPE_ENUM.outOrder.id,
				orgId: '',
				targetOrgId: '',
				isOverseasStore: '',
				countryCode: '',
				file: '',
				remark: '',
				executeStatus: '',
				executeProgress: '',
				issueTime: '',
				estimateCompletionTime: '',
				receiveTime: '',
				status: '',
				createTime: '',
				createUser: '',
				updateTime: '',
				updateUser: '',
				orderMaterials: orderMaterials,
			}
			addOutOrderForProductionOrder(orderBean).then(res => {
				console.log(`生产单出库响应结果:${res.data}`)
				if (res.success) {
					this.$message.info('出库成功')
					this.handleOk()
				} else {
					this.$message.error('出库失败：' + res.message)
				}
			})
		},
		handleCancel() {
			this.visible = false
		},
		onEmsMaterialIndex1Selected(materialRow) {
			// console.log(`选择了原料:id=${materialRow.materialId}, code=${materialRow.materialCode}, name=${materialRow.materialName}`)
			// debugger
			let { materialId, materialName, materialCode, materialType, costPrice } = materialRow
			// 需要调用接口往订单中添加物料
			let _emsOrder = Object.assign({}, this.emsOrder)
			_emsOrder.orderMaterials = []
			let orderMaterial = {
				orderMaterialId: '',
				orderId: _emsOrder.orderId,
				bomId: '0',  // 单独选择原料时没有BOMID
				materialId: materialId,
				number: 1,
				completedNumber: 0,
				executeStatus: '0',
				executeProgress: '0',
				status: '0',
				createTime: '',
				createUser: '',
				updateTime: '',
				updateUser: '',
			}
			_emsOrder.orderMaterials.push(orderMaterial)
			add(orderMaterial).then(res => {
				if (res.success) {
					this.$message.success('新增成功')
					// this.handleCancel()
					// this.$emit('ok', values)
					this.$refs.table.refresh()
				} else {
					this.$message.info('新增失败：' + res.message)
				}
			})
			// 然后刷新table控件
		},
		imageURLFormat(text) {
			return `${this.$store.state.baseUrl}/sysFileInfo/preview?id=${text}&token=${this.token}`
		}
	}
}
</script>

<style lang="less">
.table-operator {
	margin-bottom: 18px;
}

button {
	margin-right: 8px;
}
</style>
